package com.UnionPayCenter.util;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

@Data
public class HttpClient {
    private String url = null;
    private String charset = "utf-8";
    private String params = null;
    private int connectionTimeout = 15 * 1000;
    private int readTimeout = 30 * 1000;
    private String contentType = "application/x-www-form-urlencoded;charset=UTF-8";
    private String method = "post";
    private Map<String, String> headers = new HashMap<String, String>();

    public String get() {
        this.method = "GET";
        return this.service();
    }

    public String post() {
        this.method = "POST";
        return this.service();
    }

    private String service() {
        HttpURLConnection conn = null;
        InputStream in = null;
        OutputStream out = null;
        StringBuffer sb = new StringBuffer();
        try {
            // 获取连接
            URL url = new URL(this.url);
            conn = (HttpURLConnection) url.openConnection();
            // 设置连接属性
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestMethod(method.toUpperCase());
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("User-Agent", " Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");

            if (!this.headers.isEmpty()) {
                Set<Entry<String, String>> set = headers.entrySet();
                for (Entry<String, String> entry : set) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (this.params != null) {
                byte[] data = params.getBytes(charset);
                conn.setRequestProperty("Content-Length", String.valueOf(data.length));
                // 向服务器发送数据
                out = conn.getOutputStream();
                out.write(data);
                out.flush();
            }
            int code = conn.getResponseCode();
            String message = conn.getResponseMessage();
            if (HttpURLConnection.HTTP_OK == code) {
                // 读取响应
                in = conn.getInputStream();
                InputStreamReader reader = new InputStreamReader(in, charset);
                BufferedReader bufReader = new BufferedReader(reader);
                String buf = null;
                while ((buf = bufReader.readLine()) != null) {
                    sb.append(buf);
                }
                String responseString = sb.toString();
                return responseString;
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            if (null != conn) {
                conn.disconnect();
            }
        }
    }
}